package main

/*
#cgo LDFLAGS: -lportaudio

#define GOBUFSIZE 64

#include "./in.c"
*/
import "C"

import (
	"flag"
	"os"
	"reflect"
	"runtime"
	"runtime/pprof"
	"unsafe"

	"code.google.com/p/jnj/cmd/util"
)

const bufsize = 64 // this must match GOBUFSIZE above

var (
	die    = util.Die
	limit1 = 1

	cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
)

func getSamples() []int32 {
	samplesPointer, _ := C.getSamples()
	hdr := reflect.SliceHeader{
		Data: uintptr(unsafe.Pointer(samplesPointer)),
		Len:  bufsize,
		Cap:  bufsize,
	}
	samples := *(*[]int32)(unsafe.Pointer(&hdr))
	return samples
}

func putSamples(buf []int32) {
	C.putSamples((*C.SAMPLE)(unsafe.Pointer(&buf[0])))
}

func main() {
	flag.Parse()

	runtime.GOMAXPROCS(4)
	C.initPA()

	visInit()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		die(err)
		pprof.StartCPUProfile(f)
	}

	drawCounter := 0
	for {
		s := getSamples()
		s = process(s)
		if drawCounter == 5 {
			vis(s)
			drawCounter = 0
		} else {
			drawCounter++
		}
		putSamples(s)
	}
}

func process(s []int32) []int32 {
	for i := 0; i <= len(s)-limit1; i += limit1 {
		for ii := i; ii < i+limit1; ii++ {
			s[ii] = s[i]
		}
	}
	return s
}

func cleanup() {
	pprof.StopCPUProfile()
	C.shutdownPA()
	os.Exit(0)
}
